<template>
  <div v-loading="loading" class="common-chart">
    <CommonChart :options="chartOptions" height="100%" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue"
import type { EChartsOption } from "echarts"
import { CommonChart } from "@/components"
import { getEmploymentTrendDataApi } from "@/interface"
import { colorManager } from "@/utils/colorMap"

interface Props {
  provinces: string[]
}

const props = defineProps<Props>()

const loading = ref(false)
// 薪资水平对比图配置
const employmentTrendData = ref<Record<string, any>>({})
const chartOptions = computed<EChartsOption>(() => {
  if (!employmentTrendData.value || !employmentTrendData.value.provinceTrends) return {}

  // 根据 provinces 筛选省份数据
  const filteredProvinceTrends = employmentTrendData.value.provinceTrends.filter((item: any) =>
    props.provinces.includes(item.name)
  )

  const otherSeries = filteredProvinceTrends.map((item: any) => {
    return {
      name: item.name,
      type: "line",
      data: item.data.map((item: any) => item.value),
      itemStyle: {
        color: colorManager.getColor(item.name)
      },
      lineStyle: {
        color: colorManager.getColor(item.name)
      }
    }
  })

  return {
    title: {
      text: "就业率趋势",
      left: "start"
    },
    tooltip: {
      trigger: "axis"
    },
    legend: {
      data: ["全国平均", ...filteredProvinceTrends.map((item: any) => item.name)],
      type: "scroll",
      top: 0,
      right: "0%",
      width: "50%"
    },
    xAxis: {
      type: "category",
      data: employmentTrendData.value.nationalTrend.map((item: any) => item.year)
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        name: "全国平均",
        type: "line",
        data: employmentTrendData.value.nationalTrend.map((item: any) => item.value)
      },
      ...otherSeries
    ],
    grid: {
      left: "3%",
      right: "4%",
      bottom: "0%",
      top: "20%",
      containLabel: true
    }
  }
})

const getEmploymentTrendData = () => {
  loading.value = true
  getEmploymentTrendDataApi()
    .then((res: any) => {
      employmentTrendData.value = res
    })
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  getEmploymentTrendData()
})

watch(
  () => props.provinces,
  () => {
    console.log(props.provinces)
  }
)
</script>

<style scoped>
.common-chart {
  width: 100%;
  height: 100%;
}
</style>
